/*                   _   _ _ __                               *\
**     ________ ___ | | | | '_ \   scaup - Scala up!          **
**    / __/ __// _ || | | | |_) |  (c) 2008, Normen Mueller   **
**  __\ \/ /__/ __ || |_| | .__/   http://kwarc.info.nmueller **
** /____/\___/_/ |_/ \__,_|_|                                 **
**                                                            **
\*                                                            */
  
// $Id: ConsoleReporter.scala 9 2008-05-24 12:12:30Z normen.mueller $

/* This class has its origin at: scala.tools.nsc.reporters.ConsoleReporter */

package scaup.reporter

import java.io.{BufferedReader, InputStreamReader, IOException, PrintWriter}
import util._

/** This class implements a Reporter that displays messages on a text console. */
class ConsoleReporter(val settings: Settings, reader: BufferedReader, writer: PrintWriter) extends AbstractReporter {
  /** Whether a short file name should be displayed before errors */
  var shortname: Boolean = false
  
  def this(settings: Settings) = this(settings, Console.in, new PrintWriter(Console.err, true))
  
  /** Prints the message. */
  //def printMessage(msg: String) { writer.println(msg) }  // platform-dependent!
  def printMessage(msg: String) { writer.print(msg + "\n"); writer.flush() }

  def print(msg: String, severity: Severity) { printMessage(clabel(severity) + msg) }
  
  def display(msg: String, severity: Severity) {
    severity.count += 1
    print(msg, severity)
  }

  def displayPrompt: Unit = try {
    var continue = true
    while (continue) {
      writer.print("r)esume, a)bort: ")
      writer.flush()
      var line = reader.readLine()
      if (line ne null) {
        line = line.toLowerCase()
        if ("abort" startsWith line) throw new Error("user abort")
        if ("resume" startsWith line) continue = false
      }
    }
  } catch {
    case ex: IOException => {
      ex.printStackTrace()
      throw new Error("input read error")
    }
  }

  override def flush() { writer.flush() }

  /** Prints the number of errors and warnings if their are non-zero. */
  def printSummary() {
    if (WARNING.count > 0) printMessage(getCountString(WARNING) + " found")
    if (  ERROR.count > 0) printMessage(getCountString(ERROR  ) + " found")
  }

  private def label(severity: Severity): String = severity match {
    case ERROR   => "error"
    case WARNING => "warning"
    case INFO    => null
  }

  private def clabel(severity: Severity): String = {
    val label0 = label(severity)
    if (label0 eq null) "" else label0 + ": "
  }

  /** Returns the number of errors issued totally as a string.
   * @param severity ...
   * @return         ... */
  private def getCountString(severity: Severity): String = countElementsAsString((severity).count, label(severity))
}

